﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Threading;

namespace DojoTimer
{
delegate void TimerDispatcherDelegate(int elapsed);
public partial class DojoTimerWindow : Window
{
    Timer timer = null;

    int elapsed = 0;
    int tempoTotal = 300;

    public DojoTimerWindow()
    {
        InitializeComponent();
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        DefaultValues();

        timer = new Timer((obj) =>
            {
                CalculateTime();
            }, this.elapsed, 0, 1000);
    }

    private void DefaultValues()
    {
        tempo.Text = string.Format("00:00");
        elapsed = 0;
        alarme.Stop();

        this.WindowState = System.Windows.WindowState.Minimized;
            
    }

    private void CalculateTime()
    {
        this.Dispatcher.Invoke(new TimerDispatcherDelegate(tempoCorrido =>
        {
            if (tempoCorrido == tempoTotal)
            {
                alarme.Play();

                this.WindowState = System.Windows.WindowState.Maximized;
                this.Topmost = true;

                this.timer.Dispose();
            }
            else
            {
                PrintTime(tempoCorrido);
            }

        }), this.elapsed++);
    }

    private void PrintTime(int tempoCorrido)
    {
        var timeSpan = new TimeSpan(0, 0, (tempoCorrido > 60 ? tempoCorrido / 60 : 0), tempoCorrido % 60);
        tempo.Text = string.Format("{0}:{1}", (4 - timeSpan.Minutes).ToString("00"), (59 - timeSpan.Seconds).ToString("00"));
    }
}

}
